package com.efun.center.http.config;

import com.efun.center.http.handler.HttpSupport;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ProjectLoader implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, InitializingBean {

    protected ApplicationContext applicationContext;

    /**
     * 配置生成
     */
    protected ProjectConfigBuilder projectConfigBuilder;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 定义扫描器
        ServiceScanner scanner = new ServiceScanner(registry);
        scanner.init();
        scanner.scan();
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.projectConfigBuilder = new ProjectConfigBuilder();
        projectConfigBuilder.load();
    }

    /**
     * 获取远程方法映射
     *
     * @param method
     * @return
     */
    public MethodMapper getMethodMapper(String method) {
        return projectConfigBuilder.getMethodMapper(method);
    }

    /**
     * 获取处理器
     *
     * @param handlerClass
     * @return
     */
    public HttpSupport getHandler(Class<? extends HttpSupport> handlerClass) {
        return (HttpSupport) applicationContext.getBean(handlerClass);
    }

}
